package com.dddpeter.app.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dddpeter.app.entity.Article;
import com.dddpeter.app.entity.ArticleWithStats;
import com.dddpeter.app.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/articles")
@CrossOrigin(origins = "*")
public class ArticleController {
    
    @Autowired
    private ArticleService articleService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllArticles() {
        try {
            List<Article> articles = articleService.getAllArticles();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("count", articles.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章列表失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/published")
    public ResponseEntity<Map<String, Object>> getPublishedArticles() {
        try {
            List<Article> articles = articleService.getPublishedArticles();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("count", articles.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取已发布文章失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询所有文章
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getArticlesPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<Article> page = articleService.getArticlesPage(current, size);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章分页失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询已发布文章
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/published/page")
    public ResponseEntity<Map<String, Object>> getPublishedArticlesPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<Article> page = articleService.getPublishedArticlesPage(current, size);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取已发布文章分页失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页搜索文章
     * @param keyword 搜索关键词
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/search/page")
    public ResponseEntity<Map<String, Object>> searchArticlesPage(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<Article> page = articleService.searchArticlesPage(keyword, current, size);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("搜索文章分页失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getArticleById(@PathVariable Long id) {
        try {
            Optional<Article> article = articleService.getArticleById(id);
            if (article.isPresent()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("data", article.get());
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("文章不存在，ID: " + id));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/author/{authorId}")
    public ResponseEntity<Map<String, Object>> getArticlesByAuthor(@PathVariable Long authorId) {
        try {
            List<Article> articles = articleService.getArticlesByAuthor(authorId);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("count", articles.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取作者文章失败: " + e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<Map<String, Object>> createArticle(@RequestBody Article article) {
        try {
            Article createdArticle = articleService.createArticle(article);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", createdArticle);
            response.put("message", "文章创建成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("创建文章失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateArticle(@PathVariable Long id, @RequestBody Article article) {
        try {
            Article updatedArticle = articleService.updateArticle(id, article);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", updatedArticle);
            response.put("message", "文章更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("更新文章失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/publish")
    public ResponseEntity<Map<String, Object>> publishArticle(@PathVariable Long id) {
        try {
            Article article = articleService.publishArticle(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", article);
            response.put("message", "文章发布成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("发布文章失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/archive")
    public ResponseEntity<Map<String, Object>> archiveArticle(@PathVariable Long id) {
        try {
            Article article = articleService.archiveArticle(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", article);
            response.put("message", "文章归档成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("归档文章失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteArticle(@PathVariable Long id) {
        try {
            articleService.deleteArticle(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "文章删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(createErrorResponse("删除文章失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchArticles(@RequestParam String keyword) {
        try {
            List<Article> articles = articleService.searchArticles(keyword);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("count", articles.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("搜索文章失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询指定分类的文章
     * @param category 分类值
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/category/page")
    public ResponseEntity<Map<String, Object>> getArticlesByCategoryPage(
            @RequestParam String category,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<Article> page = articleService.getArticlesByCategoryPage(category, current, size);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取分类文章分页失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询指定多个分类的文章
     * @param categories 分类列表（逗号分隔）
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/categories/page")
    public ResponseEntity<Map<String, Object>> getArticlesByCategoriesPage(
            @RequestParam String categories,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 将逗号分隔的字符串转换为列表
            List<String> categoryList = Arrays.asList(categories.split(","));
            IPage<Article> page = articleService.getArticlesByCategoriesPage(categoryList, current, size);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", page.getRecords());
            response.put("current", page.getCurrent());
            response.put("size", page.getSize());
            response.put("total", page.getTotal());
            response.put("pages", page.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取多分类文章分页失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getArticleStats() {
        try {
            long totalArticles = articleService.getTotalArticleCount();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("totalArticles", totalArticles);
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询已发布文章并包含热度和评论数统计
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/published/page/stats")
    public ResponseEntity<Map<String, Object>> getPublishedArticlesPageWithStats(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<ArticleWithStats> articles = articleService.getPublishedArticlesWithStats(current, size);
            long total = articleService.getPublishedArticlesCount();
            long totalPages = (total + size - 1) / size;
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("current", current);
            response.put("size", size);
            response.put("total", total);
            response.put("pages", totalPages);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取文章列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询指定分类的文章并包含热度和评论数统计
     * @param category 分类值
     * @param current 当前页码（从1开始）
     * @param size 每页大小
     */
    @GetMapping("/category/page/stats")
    public ResponseEntity<Map<String, Object>> getArticlesByCategoryPageWithStats(
            @RequestParam String category,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<ArticleWithStats> articles = articleService.getArticlesByCategoryWithStats(category, current, size);
            long total = articleService.getPublishedArticlesCountByCategory(category);
            long totalPages = (total + size - 1) / size;
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", articles);
            response.put("current", current);
            response.put("size", size);
            response.put("total", total);
            response.put("pages", totalPages);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取分类文章列表失败: " + e.getMessage()));
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("error", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}
